package cn.tedu.mall.seckill.interceptor;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderItemAddDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 验证是否重复秒杀
 */
@Component
@Order(10)
public class ReseckillInterceptor implements SeckillInterceptor{
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 重复秒杀：同一个用户，下单抢购同一个skuId就是重复秒杀
     * 将 userId 和 skuId 组合成一个key值，在redis中调用incr命令，如果返回值>1，说明重复秒杀了
     * @param seckillOrderAddDTO spuId
     */
    @Override
    public void seckillCommitCheck(SeckillOrderAddDTO seckillOrderAddDTO) {
        Long userId = seckillOrderAddDTO.getUserId();
        SeckillOrderItemAddDTO seckillOrderItemAddDTO = seckillOrderAddDTO.getSeckillOrderItemAddDTO();
        Long skuId = seckillOrderItemAddDTO.getSkuId();
        String repeatKey = "seckill:" + userId + ":" + skuId;
        Long times = stringRedisTemplate.opsForValue().increment(repeatKey);
        if (times > 1) {
            throw new CoolSharkServiceException(ResponseCode.FORBIDDEN, "当前用户重复秒杀！");
        }
    }
}
